package com.liuc.task.cluster.demo.task2.timed;

import com.liuc.task.cluster.demo.task2.factory.ProxyFactory;
import com.liuc.task.cluster.demo.task2.middle.ware.Lock;
import com.liuc.task.cluster.demo.task2.service.TaskService;
import com.liuc.task.cluster.demo.task2.service.TaskServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class TaskSchedule {

    @Autowired
    private ProxyFactory proxyFactory;

    @Autowired
    private TaskService taskService;

    private int i = 100;

    @Scheduled(cron = "*/5 * * * * ?")
    public void execute() {
        int intKey = i--;
        String key = "key-" + intKey;
        String value = "name-" + key;
        TaskService proxyObject = getTaskServiceProxyObject("event");
        proxyObject.insertUserTask(key, value);
    }

    /**
     * 设置 Lock name 是因为会有不同的任务，标识不同任务
     * 设置 uuid 是因为会有多个服务，标识不同服务
     * @param key
     * @return
     */
    private TaskService getTaskServiceProxyObject(String key) {
        String uuid = UUID.randomUUID().toString();
        Lock redisLock = getLockWithKeyValue(key, uuid);
        redisLock.setTimeout(5L);
        redisLock.setTimeUnit(TimeUnit.MINUTES);

        return  (TaskService)proxyFactory.getProxyObject(this.taskService, redisLock, uuid);
    }

    private Lock getLockWithKeyValue(String lockName, String uuid) {
        Lock redisLock = new Lock();

        redisLock.setName(lockName);
        redisLock.setValue(lockName + "-" + uuid);

        return redisLock;
    }

}

